package router

import (
	"context"
	"gitee.com/xiedongji/go-core/conf"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"time"
)

var HttpServerHandler *http.Server

func HttpServerRun() {

	gin.SetMode(conf.IConfBase.Base.DebugMode)
	//f, _:= os.Create("./test.log")
	//gin.DefaultWriter = io.MultiWriter(f)
	routerHandler := InitRouterHandler()
	HttpServerHandler = &http.Server{
		Addr:           conf.IConfBase.Http.Addr,
		Handler:        routerHandler,
		ReadTimeout:    time.Duration(conf.IConfBase.Http.ReadTimeout) * time.Second,
		WriteTimeout:   time.Duration(conf.IConfBase.Http.WriteTimeout) * time.Second,
		MaxHeaderBytes: 1 << uint(conf.IConfBase.Http.MaxHeaderBytes),
	}

	go func() {
		log.Printf("[INFO] HttpServer Listen On %s\n", conf.GetStringConf("base.ihttp.addr"))
		log.Println("---------------------------------------------------------")
		if err := HttpServerHandler.ListenAndServe(); err != nil {
			log.Fatalf("[ERROR] HttpServer Listen Fail %s err:%v\n", conf.GetStringConf("base.ihttp.addr"), err)
		}
	}()

}

func HttpServerStop() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := HttpServerHandler.Shutdown(ctx); err != nil {
		log.Fatalf("[ERROR] HttpServer 关闭报错:%v\n", err)
	}
	log.Printf("[INFO] HttpServer 服务 关闭中.... ^_^!\n")
}
